<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>

    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>

    <!-- <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template> -->

    <template v-slot:table>
      <TableData v-if="!searchFormData.dealFlag" :config="table_config" :tableThead="tableThead" :dataList="dataList"
        :loading="loading" @selection-change="selectionChange">
        <template v-slot:batchName="{ row }">
          {{ batchObj[row.batchId] }}
        </template>
      </TableData>
      <TableData v-if="searchFormData.dealFlag && !searchFormData.completeFlag" :config="table_config_completeFlag"
        :tableThead="tableThead" :dataList="dataList" :loading="loading" @selection-change="selectionChange">
        <template v-slot:batchName="{ row }">
          {{ batchObj[row.batchId] }}
        </template>
        <template v-slot:handlingRecord="{ row }">
          <span @click="handleLookView(row, true)">有处方</span>
          <span @click="handleLookView(row, false)">无处方</span>
        </template>
      </TableData>
    </template>

    <template v-slot:pagination>
      <Pagination  @size-Change="handleSizeChange" :size="size"  @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>

    <template v-slot:dialogModule>
      <AddEdit :title="'疾病记录'" @closeDialog="closeDialog" :diseaseList="diseaseList" :batchList="batchList"
        :facilityList="facilityList" :varietyList="varietyList" :materialList="materialList" :addEditFlag="addEditFlag"
        :dialogVisible="dialogVisible" :data="formData" :diseaseBankPrescription="diseaseBankPrescription">
      </AddEdit>
      <el-dialog :close-on-click-modal="false"  title="用药记录" :visible.sync="drugDialogVisible" width="60%" :before-close="handleClose" >
        <div v-if="usePrescription" class="usePrescriptionDrugData">
          <div class="prescriptionName">
            <p>处方名称：{{ prescriptionInfo.prescriptionName }}</p>
            <p>用药天数：{{ prescriptionInfo.days }}</p>
          </div>
          <div class="drugDataList">
            <div class="drugData" v-if="prescriptionInfo.days">
              <div class="drugDataItem" v-for="day, dayIndex in Array.from({ length: prescriptionInfo.days }, (_, i) => i + 1)"
                :key="dayIndex">
                <div class="title">第{{ day }}天用药：</div>
                <div class="tableInfo">
                  <span class="title">用药信息：</span>
                  <div class="durgInfo">
                    <div v-show="day == item.days" v-for="item, index in prescriptionInfo.drugDetailList" :key="index">
                      <span class="label">药品名称：{{ item.materialName }}</span>
                      <span class="label">用药量：{{ item.num }}{{ item.unitName }}/平方米</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="drugData">
              <div class="drugDataItem" v-for="item, index in usePrescriptionDrugData" :key="index">
                <div class="tableInfo">
                  <span class="title">用药信息：</span>
                  <div class="durgInfoList">
                    <div class="durgInfo" v-for="e, i in item.diseaseDealDetailList" :key="i">
                      <span class="label">药品名称：{{ e.materialName }}</span>
                      <span class="label">用药量：{{ e.amount }}{{ e.unitName }}</span>
                    </div>
                  </div>
                </div>
                <div class="tableInfo">
                  <span class="title">用药时间：</span>
                  <div>{{ item.dealDate }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="!usePrescription" class="usePrescriptionDrugData">
          <el-table :data="drugData" :expand-row-keys="expends" :row-key="getRowKeys" style="width: 100%" border
            height="500px">
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column prop="staffName" label="处理人">
            </el-table-column>
            <el-table-column label="用药时水温" width="180">
              <template slot-scope="scope">
                {{ scope.row.waterTemperature }}℃
              </template>
            </el-table-column>
            <el-table-column prop="dealDate" label="用药时间">
            </el-table-column>
            <el-table-column type="expand" :default-expand-all="true">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <div class="durgInfoList">
                    <div class=" durgInfo" v-for="item, index in props.row.diseaseDealDetailList" :key="index">
                      <div class="label">药品名称：{{ item.materialName }}</div>
                      <div class="label">用药量：{{ item.amount }}{{ item.unitName }}</div>
                    </div>
                  </div>
                </el-form>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="drugDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="drugDialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import AddEdit from './components/addEdit.vue';
import diseaseRecord from '@/api/healthManagement/diseaseRecord.js';
import diseaseManagement from '@/api/diseaseBankManagement/diseaseManagement.js';
import specificationManagement from '@/api/basicInformation/specificationManagement.js';
import facilityManagement from '@/api/digtalOperation/facilityManagement.js';
import varietyManagement from '@/api/basicInformation/varietyManagement.js';
import prescription from '@/api/healthManagement/prescription.js';
import diseaseFollowUp from '@/api/healthManagement/diseaseFollowUp.js';
import batch from '@/api/batch/batchManagement';
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料

export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit },
  data() {
    return {
      drugDialogVisible: false,
      resetTable: false,
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      viewFlag: false,
      addEditFlag: 'add',
      formData: {},
      batchObj: {},
      searchFormData: {
        dealFlag: false,
        completeFlag: false,
      },
      drugData: [],
      page: 1,
      size:10,
      total: 199,
      selectIndex: 0,
      btnList: ['add', 'delete'],
      enumList: [{
        label: "未处理",
        id: 1,
        flag: 'dealFlag',
      },
      {
        label: "已处理",
        id: 2,
        flag: 'dealFlag',
      }],
      dataList: [],
      tableThead: [
        { isShow: true, label: '疾病名称', prop: 'diseaseName' },
        { isShow: true, label: '患病粒数', prop: 'num' },
        { isShow: true, label: '发现疾病设施', prop: 'facilityName' },
        { isShow: true, label: '批次名称', slotName: 'batchName' },
        { isShow: true, label: '疾病上报人', prop: 'staffName' },
        { isShow: true, label: '发现时间', prop: 'happenTime' },
        { isShow: true, label: '处理记录', slotName: 'handlingRecord' }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '处理',
              type: 'primary',
              flag: 'handle',
              handleRow: this.handleRow
            }
          ]
        },
      },
      // 配置项
      table_config_completeFlag: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '继续处理',
              type: 'primary',
              flag: 'cProc',
              handleRow: this.handleRow
            },
            {
              label: '完成',
              type: 'warning',
              flag: 'complete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      diseaseBankPrescription: [],
      varietyList: [],
      facilityList: [],
      batchList: [],
      specificationList: [],
      prescriptionList: [],
      diseaseList: [],
      materialList: [],
      expends: [],
      prescriptionInfo: {},
      usePrescriptionDrugData: [],
      usePrescription: false,
      formItemList: [
        {
          label: '养殖设施',
          type: 'select',
          selectOptions: [],
          param: 'facilityId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '批次名称',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '上报人',
          type: 'select',
          selectOptions: [],
          param: 'staffName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '发现日期',
          type: 'datetimerange',
          param: 'dateTime',
          multiple: false,
          isShow: true
        }
      ]
    }
  },
  computed: {
    person() {
      return this.$store.state.initData.person || [];
    },
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },
  methods: {
    async initData() {
      let { data: prescriptionList } = await prescription.queryByCondition();
      let { data: materialList } = await materialApi.getqueryList({});
      this.materialList = materialList;
      this.prescriptionList = prescriptionList;
      this.materialList = this.materialList.filter(data => {
        return data.materialTypeNo == '4165464165465146516' || data.materialTypeNo == '1077222993386450944'
      })
      let { data: diseaseList } = await diseaseManagement.queryByCondition({})
      this.diseaseList = diseaseList
      let { data: specificationList } = await specificationManagement.queryByCondition({});
      this.specificationList = specificationList;
      // 获取批次列表 
      let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' });
      this.batchList = batchList;
      this.batchObj = {};
      this.batchList.forEach(item => {
        this.batchObj[item.batchId] = item.batchName
      })
      //获取品种；
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      this.varietyList = varietyList || [];
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
      this.setFormOptions();
    },

    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityId') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchId') !== -1) {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'staffName') {
          let selectOptions = this.person.map(data => {
            return {
              text: data.person.name, value: data.person.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    getExpends() {
      var Id = this.drugData.map(item => item.diseaseDealId)
      this.expends = Id
    },
    getRowKeys(row) {
      return row.diseaseDealId
    },
    //falg  是否有处方
    async handleLookView(row, flag) {
      let { diseaseRecordId } = row
      this.usePrescription = flag;
      let { data: durgList } = await diseaseFollowUp.queryByCondition({ diseaseRecordId });
      console.log(durgList)
      if (flag) {
        this.diseaseBankPrescription = this.prescriptionList.filter(e => {
          return e.diseaseRecordId == diseaseRecordId
        })
        this.prescriptionInfo = this.diseaseBankPrescription.length ? this.diseaseBankPrescription[0] : {}
        console.log(this.prescriptionInfo)
        let usePrescriptionList = []
        usePrescriptionList = durgList.filter(e => e.prescriptionId)
        this.drugDialogVisible = true;
        usePrescriptionList.sort((a,b)=>{
          return new Date(a.dealDate) - new Date(b.dealDate)
        })
        this.usePrescriptionDrugData = usePrescriptionList;
        console.log('有处方：', usePrescriptionList)
      } else {
        let notUsePrescriptionList = []
        notUsePrescriptionList = durgList.filter(e => !e.prescriptionId)
        this.drugData = notUsePrescriptionList
        this.drugDialogVisible = true;
        this.getExpends();
        console.log('无处方：', notUsePrescriptionList)
      }
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      this.page = 1;
      this.selectIndex = enumInfo.index || 0;
      console.log(enumInfo.data.id)
      if (enumInfo.data.id == 1) {
        this.$set(this.searchFormData, 'dealFlag', false);
        this.$set(this.searchFormData, 'completeFlag', false);
      } else if (enumInfo.data.id == 2) {
        this.$set(this.searchFormData, 'dealFlag', true);
        this.$set(this.searchFormData, 'completeFlag', false);
      } else if (enumInfo.data.id == 3) {
        this.$set(this.searchFormData, 'dealFlag', true);
        this.$set(this.searchFormData, 'completeFlag', true);
      }
      this.enunLabel = enumInfo.data.label
      this.queryPageByCondition();
    },
    // diseaseManagement
    delList(deleteList = [], key = 'diseaseRecordId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await diseaseRecord.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData
        }
      }
      this.resetTable = false;
      diseaseRecord.queryPageByCondition(params).then(res => {
        this.resetTable = true;
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    search(data) {
      this.page = 1;
      let endData = null;
      let startData = null;
      if (data.dateTime && data.dateTime.length == 2) {
        startData = `${data.dateTime[0]} 00:00:00`;
        endData = `${data.dateTime[1]} 23:59:59`;
      }
      this.searchFormData = {
        ...this.searchFormData,
        ...data,
        endTime: endData,
        startTime: startData
      };
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == 'handle' || item.flag == 'cProc') {
        this.dialogVisible = true;
        this.diseaseBankPrescription = this.prescriptionList.filter(e => {
          return e.diseaseRecordId == rowData.diseaseRecordId
        })
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'complete') {
        this.finish(rowData.diseaseRecordId)
      }
      this.addEditFlag = item.flag
    },
    finish(id) {
      this.$confirm('确定要完成改记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await diseaseRecord.complete(id);
        if (res.code == 1) {
          this.$message.success(res.msg || '操作成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '操作失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    }
  }
};
</script>

<style lang="scss" scoped>
.pointer {
  cursor: pointer;
}

.demo-table-expand {
  .durgInfoList {
    padding: 15px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;

    .durgInfo {
      margin-right: 10px;
      background-color: #ededed;
      padding: 10px;
      font-size: 14px;
      line-height: 28px;
    }
  }
}
.usePrescriptionDrugData{
  max-height: 600px;
  overflow: auto;
  .prescriptionName{
    font-size: 18px;
    padding: 0 15px;
  }

  .drugDataList {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  font-size: 16px;
  .drugDataItem{
    margin-bottom: 10px;
    background-color: #f4f4f4;
    padding: 15px;
    border: 1px solid #cecece;
  }

  .title {
    font-size: 18px;
    font-weight: bold;
  }

  .drugData {
    width: 50%;
    padding: 10px;
    line-height: 40px;


    &:last-child {
      border-left: 1px solid #d7d7d7;
    }

    .tableInfo {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;

      .title {
        font-size: 16px;
      }
    }
  }
}
}
</style>